#include "socketmanager.h"



SocketManager *SocketManager::instance()
{
    static SocketManager* ins = new SocketManager();
    return ins;
}

QTcpSocket *SocketManager::getsocket()
{
    return socket;
}

void SocketManager::connectToServer()
{
    if(socket->state() == QAbstractSocket::UnconnectedState)
    {
        socket->connectToHost("127.0.0.1",8081);

    }
}

void SocketManager::onReadyRead()
{
    while(socket->canReadLine())
    {
        QByteArray data = socket->readLine().trimmed();
        QJsonParseError error;
        QJsonDocument doc = QJsonDocument::fromJson(data,&error);

        if(error.error != QJsonParseError::NoError || !doc.isObject())
        {

        }


        QJsonObject json = doc.object();
        int type = json["MessageType"].toInt();

        switch (type) {
           case static_cast<int>(Protocol::ResponseType::Res_Login):
               emit loginResponse(json);
               break;
           case static_cast<int>(Protocol::ResponseType::Res_Registe):
               emit registerResponse(json);
               break;
           case static_cast<int>(Protocol::ResponseType::Res_Chat):
               emit chatMessage(json);
               break;
           case static_cast<int>(Protocol::ResponseType::Res_ServerBroadcast):
               emit serverBroadcast(json);
               break;
           default:
               qWarning("未识别的 MessageType: %d", type);
               break;
        }

    }
}

SocketManager::SocketManager(QObject *parent)
{
    socket = new QTcpSocket(this);
    connect(socket,&QTcpSocket::readyRead,this,&SocketManager::onReadyRead);
}

